package com.mycompany.j2eem.service.common;

/**
 *
 * @author wucy
 */
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class Ftp {

    public List<String> testFtpClient(List<MultipartFile> mFile) throws Exception {
        List<String> listName = new ArrayList<>();
        //创建一个FtpClient对象
        FTPClient ftpClient = new FTPClient();
        //创建ftp连接，默认是：21端口
        ftpClient.connect("47.94.165.133", 21);
        //登录ftp服务器，使用用户名 和密码
        ftpClient.login("wucy2", "123456");
        //上传文件
        //读取本地文件
        for(int i = 1;i <= mFile.size();i++){
            Date t = new Date();
            long nm = System.nanoTime();
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String name = i + nm+ mFile.get(i-1).getName() + ".png";
            listName.add(name);
            //转换为InputStream
            CommonsMultipartFile cFile = (CommonsMultipartFile) mFile.get(i-1);
            DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
            InputStream inputStream = null;
            
            try {
                inputStream = fileItem.getInputStream();
            } catch (IOException ex) {
                Logger.getLogger(Ftp.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                //        FileInputStream inputStream = new FileInputStream(
                //                new File("D:\\Picture\\wife.jpg"));
                //设置上传的路径
                //        ftpClient.changeWorkingDirectory("http://47.94.165.133/images/");
                //修改上传文件的格式
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            } catch (IOException ex) {
                Logger.getLogger(Ftp.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                //第一个参数：服务器端文档名
                //第二个参数：上传文档的inputStream});
                ftpClient.storeFile(name, inputStream);
            } catch (IOException ex) {
                Logger.getLogger(Ftp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
     
        //关闭连接
        ftpClient.logout();
        return listName;
    }
}
